package com.lr.wfxmanager.merchant.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.lr.wfxmanager.bean.JsonResultVo;
import com.lr.wfxmanager.bean.UserDTO;


import com.lr.wfxmanager.bean.WxbGood;
import com.lr.wfxmanager.bean.WxbOrder;
import com.lr.wfxmanager.merchant.service.IMerchantService;
import io.goeasy.GoEasy;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

@RestController
@RequestMapping("merchant")
public class MerchantController {
    @Resource
    private IMerchantService iMerchantService;
    /*处理商户登录*/
    private Logger logger = Logger.getLogger(MerchantController.class.getName());
    @RequestMapping("login")
    public JsonResultVo login(@RequestBody UserDTO userDTO){
        JsonResultVo resultVo = new JsonResultVo();
        logger.info("userDTO:"+userDTO.getUsername());
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userDTO.getUsername(), userDTO.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
            resultVo.setMark(1);
        } catch (AuthenticationException e) {
            resultVo.setMark(0);
            e.printStackTrace();
        }
        return resultVo;
    }
    //自媒体提交订单
    @RequestMapping("subOrder")
    public JsonResultVo subOrder(@RequestBody WxbOrder order, HttpSession session){
        JsonResultVo resultVo = new JsonResultVo();
        logger.info("order:"+order.getAddress());
        try {
            //商家在平台存储订单,结合微信接口,获取二维码
            String code_url = iMerchantService.addOrder(order);
            System.out.println("生成:"+code_url);
            //利用zxing框架生成二维码图片返回
            session.setAttribute("code",code_url);
            resultVo.setMark(1);
            resultVo.setMsg(code_url);
        } catch (Exception e) {
            resultVo.setMark(0);
            e.printStackTrace();
            //异常界面拦截
        }

        return resultVo;
    }
    //接受微信提醒
    @RequestMapping("notify_url")
    public void notifyUrl(HttpServletResponse response, HttpServletRequest request){
        //获取通知
        try {
            ServletInputStream is = request.getInputStream();
            if (null == is){
                //通知网页不跳转
                GoEasy goEasy = new GoEasy("http://rest-hangzhou.goeasy.io", "BC-37062195321d425da33335e69cbda0b8");
                goEasy.publish("finish", null);
                return;
            }
            byte[] bys = new byte[8192];
            StringBuilder stringBuilder = new StringBuilder();
            int len = 0 ;
            while ((len = is.read(bys) )!= -1){
                String s = new String(bys, 0, len);
                stringBuilder.append(s);
            }
            //受到微信通知
            System.out.println(stringBuilder.toString());
            //支付成功,改变订单状态
            try {
                Map<String, String> xmlToMap = WXPayUtil.xmlToMap(stringBuilder.toString());
                String trade_no = xmlToMap.get("out_trade_no");//orderId
                iMerchantService.updateOrderState(1,trade_no);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //通知网页跳转
            GoEasy goEasy = new GoEasy("http://rest-hangzhou.goeasy.io", "BC-37062195321d425da33335e69cbda0b8");
            goEasy.publish("finish", "http://localhost:8086/page/myOrders");
            //回复微信
            response.getWriter().println("<xml>\n" +
                    "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "   <return_msg><![CDATA[OK]]></return_msg>\n" +
                    "   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>\n" +
                    "   <mch_id><![CDATA[10000100]]></mch_id>\n" +
                    "   <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>\n" +
                    "   <openid><![CDATA[oUpF8uMuAJO_M2pxb1Q9zNjWeS6o]]></openid>\n" +
                    "   <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>\n" +
                    "   <result_code><![CDATA[SUCCESS]]></result_code>\n" +
                    "   <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>\n" +
                    "   <trade_type><![CDATA[JSAPI]]></trade_type>\n" +
                    "</xml>");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**商家添加商品
     * 页面传入为json字符串
     *  需要用requestBody来接受,解析来对应goodsbean中的字段
     * @param goodsBean
     * @return
     */

    @RequestMapping("add")
    public JsonResultVo add(@RequestBody WxbGood goodsBean){
        logger.info("goodsBean:"+goodsBean.getGoodPic());
        JsonResultVo jsonResultVo = new JsonResultVo();
        try {
            iMerchantService.addGoods(goodsBean);
            jsonResultVo.setMark(1);
        } catch (Exception e) {
            jsonResultVo.setMark(0);
            e.printStackTrace();
        }

        return jsonResultVo;
    }
}
